package egovframework.npqs.pqi.mobile.activity.exportquarantineresult;

import java.io.File;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.activity.BuKipActivity;
import egovframework.npqs.pqi.mobile.activity.FruitPackingActivity;
import egovframework.npqs.pqi.mobile.activity.PlaceOfficerActivity;
import egovframework.npqs.pqi.mobile.activity.approve.ApproveDetail;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsoncontent.ExportQuarantineResultDetailItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.BodySeListItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.QuarantineDetailListItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.QunCdItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.ResultFlagListItem;
import egovframework.npqs.pqi.mobile.jsonparser.ExportQuarantineResultDetailThread;
import egovframework.npqs.pqi.mobile.jsonparser.ExportQuarantineResultDetailThread.ExportQuarantineResultDetailThreadCallback;
import egovframework.npqs.pqi.mobile.jsonparser.ExportQuarantineUpdateThread;
import egovframework.npqs.pqi.mobile.jsonparser.ExportQuarantineUpdateThread.ExportQuarantineUpdateThreadCallBack;

//수출검역결과등록(수출검역대기조회 상세)
public class ExportQuarantineResultDetail extends Activity implements OnClickListener
	, ExportQuarantineResultDetailThreadCallback, ExportQuarantineUpdateThreadCallBack{
	private Context context;
	
	//참조클래스
	private AppStatus myapp;
	private ExportQuarantineResultDetailThread dThread;
	private ExportQuarantineResultDetailAdapter dAdapter;
	private ExportQuarantineResultDetailItem exportItem;
	private ExportQuarantineUpdateThread updateItem;
	
	//헤더와 상단검색 부분
	private ImageButton btnLeftMenu, btnHome, btn_back;
	private TextView headerTitleText, navigation;
	private EditText edit_offcd, edit_request_num;
	private ImageButton search_btn;
	
	//본문
	private TextView text_2_1, text_2_2; //검역결과번호, 진행상태
	private TextView text_3_1; //업체명
	private TextView text_4_1, text_4_2; //수출입업자, 연락처
	private TextView text_5_1; //수출입국가
	private EditText edit_6_1; //검역장소
	private EditText edit_7_1, edit_7_2; //현장검역관
	private ImageButton button_7_1, button_7_2; //현장검역관 버튼
	private RadioButton radio_8_1, radio_8_2, radio_8_3; //검역결과 버튼3개
	private TextView string_success, fail, delay;//검역결과 텍스트 3개
	private EditText edit_9_1; //Distinguish mark
	private EditText edit_10_1, edit_10_2; //부기사항
	private ImageButton button_10_1; //부기사항
	private EditText edit_11_1; //검역관종합의견
	
	//하단부분
	private Button footer01Btn, footer02Btn, footer03Btn, footer04Btn;
	
	//리스트부분
	private ListView listView;
	private TextView headerTotTxt;
	private ImageButton upBtn, downBtn;
	
	//하단 리스트 해더
	private LinearLayout list_header_Layout;
	
	//상수
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	private final static int MSG_QUARANTINE_UPDATE_COMPLETED = 3;
	
	//기타
	private Intent intent;
	private Uri n;//전화걸기
	private String recNo, success;
	private String userSn1, userSn2;
	private String checkReqIsNull;
	private String resSeq;

	//RES043
	private ArrayList<ResultFlagListItem> resultFlagList;//검역결과코드리스트
	private ArrayList<QuarantineDetailListItem> prodArrList;//품목정보
	//스피너에담을 것
	private ArrayList<QunCdItem> quncdArrList;//수량단위리스트
	private ArrayList<String> spinQunArrList;
	private ArrayAdapter<String> qunAdapter;
	//lmo스피너
	private ArrayList<BodySeListItem> lmoArrList;
	private ArrayList<String> spinLmoArrList;
	private ArrayAdapter<String> lmoAdapter;
	//lmo 저장시 보낼 code, codeNm
	private ArrayList<String> code;
	private String codeNm;
	
	//사진
	private RelativeLayout detail_layout13_1, photo_check_mgs;
	private ImageView photo_view, photo_view2;
	private ImageButton button_13_1, button_13_2;
	private String castString1, castString2;
	private Drawable drawable1, drawable2;
	private String url1, url2;
	
	private boolean firstLoad;
	private ArrayList<String> arrInsQty;
	
	private String mResult;
	
	/* G-MOBILE 변수*/
    private String temp;
    private String requestNum;
    
    JSONObject resultDetail = new JSONObject();
	JSONObject resultData = new JSONObject();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("수출검역결과등록");
		arrInsQty = new ArrayList<String>();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_quarantine_export_result_detail);
		
		context = this;
		myapp = (AppStatus) getApplicationContext();
		
		intent = getIntent();
		recNo = intent.getStringExtra("recNo");
		Log.i("recNo", "recNo : "+recNo);
		
		userSn1 = myapp.getLoginItem().getUserSn(); 
		userSn2 = "";
		castString1="";
		castString2="";
		firstLoad=true;
		code = new ArrayList<String>();
		
		init();
	}
	
	private void init(){
		myapp.startBroker(context);
		//헤더와 상단검색 부분
		
		//하단 리스트 해더
		list_header_Layout = (LinearLayout)findViewById(R.id.list_header_Layout);
		list_header_Layout.setVisibility(View.VISIBLE);
		
		btnLeftMenu = (ImageButton)findViewById(R.id.btnLeftMenu);
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		/*btnLogin = (ImageButton)findViewById(R.id.btnLogin);*/
		search_btn = (ImageButton)findViewById(R.id.search_btn);
		headerTitleText = (TextView)findViewById(R.id.headerTitleText);
		edit_offcd = (EditText)findViewById(R.id.edit_offcd);
		edit_request_num = (EditText)findViewById(R.id.edit_request_num);
		//본문
		text_2_1 = (TextView)findViewById(R.id.text_2_1);//검역결과번호
		text_2_2 = (TextView)findViewById(R.id.text_2_2);//진행상태
		text_3_1 = (TextView)findViewById(R.id.text_3_1);//업체명
		text_4_1 = (TextView)findViewById(R.id.text_4_1);//수출입업자
		text_4_2 = (TextView)findViewById(R.id.text_4_2);//연락처
		text_5_1 = (TextView)findViewById(R.id.text_5_1);//수출입국가
		edit_6_1 = (EditText)findViewById(R.id.edit_6_1);//검역장소
		edit_7_1 = (EditText)findViewById(R.id.edit_7_1);//현장검역관
		edit_7_2 = (EditText)findViewById(R.id.edit_7_2);//현장검역관
		button_7_1 = (ImageButton)findViewById(R.id.button_7_1);//현장검역관 버튼
		button_7_2 = (ImageButton)findViewById(R.id.button_7_2);//현장검역관 버튼
		radio_8_1 = (RadioButton)findViewById(R.id.radio_8_1);//검역결과 버튼3개
		radio_8_2 = (RadioButton)findViewById(R.id.radio_8_2);//검역결과 버튼3개
		radio_8_3 = (RadioButton)findViewById(R.id.radio_8_3);//검역결과 버튼3개
		string_success = (TextView)findViewById(R.id.string_success);//검역결과 텍스트3개
		fail = (TextView)findViewById(R.id.fail);//검역결과 텍스트3개
		delay = (TextView)findViewById(R.id.delay);//검역결과 텍스트3개
		edit_9_1 = (EditText)findViewById(R.id.edit_9_1);//Distinguish mark
		edit_10_1 = (EditText)findViewById(R.id.edit_10_1);//부기사항번호
		edit_10_2 = (EditText)findViewById(R.id.edit_10_2);//부기사항텍스트
		button_10_1 = (ImageButton)findViewById(R.id.button_10_1);//부기사항
		edit_11_1 = (EditText)findViewById(R.id.edit_11_1);//검역관종합의견
		footer01Btn = (Button)findViewById(R.id.footer01Btn);//하단부분
		footer02Btn = (Button)findViewById(R.id.footer02Btn);//하단부분
		footer03Btn = (Button)findViewById(R.id.footer03Btn);//하단부분
		footer04Btn = (Button)findViewById(R.id.footer04Btn);//하단부분
		listView = (ListView)findViewById(R.id.exp_detail_list);//하단상세리스트
		
		//사진
		detail_layout13_1 = (RelativeLayout) findViewById(R.id.detail_layout13_1);
		photo_check_mgs = (RelativeLayout) findViewById(R.id.photo_check_mgs);
		photo_view = (ImageView) findViewById(R.id.photo_view);
		photo_view2 = (ImageView) findViewById(R.id.photo_view2);
		button_13_1 = (ImageButton) findViewById(R.id.button_13_1);
		button_13_2 = (ImageButton) findViewById(R.id.button_13_2);
		castString1="";
		castString2="";
		
		btn_back = (ImageButton)findViewById(R.id.btn_back);
		btn_back.setVisibility(View.VISIBLE);
		btn_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		
		//리스너 부착
		/*btnLogin.setOnClickListener(this);*/
		btnHome.setOnClickListener(this);
		search_btn.setOnClickListener(this);
		text_4_2.setOnClickListener(this);
		edit_7_1.setOnClickListener(this);
		edit_7_2.setOnClickListener(this);
		button_7_1.setOnClickListener(this);
		button_7_2.setOnClickListener(this);
		edit_10_1.setOnClickListener(this);
		button_10_1.setOnClickListener(this);
		
		//footer01Btn.setOnClickListener(this);
		footer01Btn.setBackgroundResource(R.drawable.f_blank_sel);
		//사진막기
		//footer04Btn.setBackgroundResource(R.drawable.f_blank_sel);
		
		footer02Btn.setOnClickListener(this);
		footer03Btn.setOnClickListener(this);
		footer04Btn.setOnClickListener(this);
		
		//타이틀 부착
		headerTitleText.setText("수출검역결과등록");
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		
		//셋팅
		dAdapter = new ExportQuarantineResultDetailAdapter();
		edit_offcd.setText(myapp.getLoginItem().getOffCd());
		edit_request_num.setText(recNo);
		btnLeftMenu.setVisibility(View.GONE);
		//btnHome.setVisibility(View.GONE);
		text_4_2.setPaintFlags(text_4_2.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
		
		myapp.showDialogNo(context);
		temp = "처음검색";
		//asyncTaskIsConnectedVPN();
		threadStart();
		
	}
	
	private void searchDetail(String requestNum){
		myapp.showDialogNo(context);
		this.requestNum = requestNum;
		temp = "조건검색";
		myapp.utilm.InputKeybordHidden(context, edit_request_num);
		//asyncTaskIsConnectedVPN();
		threadStart();
	}
	
	public void threadStart(){
		if("조건검색".equals(temp)){
    		dThread = new ExportQuarantineResultDetailThread(context, this
    				, myapp.getLoginItem().getOffCd(), requestNum, AppStatus.getmUserId());
    		dThread.start();
    	}
    	if("처음검색".equals(temp)){
    		dThread = new ExportQuarantineResultDetailThread(context, this
    				, myapp.getLoginItem().getOffCd(), recNo, AppStatus.getmUserId());
    		dThread.start();
    	}
    	if("저장".equals(temp)){
    		updateItem = new ExportQuarantineUpdateThread(context, this, resultData.toString()
    				, resultDetail.toString(), AppStatus.getmUserId());
    		updateItem.start();
    	}
	}

	private void layoutSetting() {
		text_2_1.setText(exportItem.getResNo());//검역결과번호
		text_2_2.setText(exportItem.getResultProgrsNm());//진행상태
		text_3_1.setText(exportItem.getVenNm());//업체명
		text_4_1.setText(exportItem.getVenRep());//수출입업자
		text_4_2.setText(exportItem.getVenTelNo());//연락처
		text_5_1.setText(exportItem.getNatNm());//수출입국가
		edit_7_1.setText(exportItem.getQuranNm1());//현장검역관
		edit_7_2.setText(exportItem.getQuranNm2());//현장검역관
		if(firstLoad){
			edit_6_1.setText(exportItem.getInsPlace());//검역장소
			edit_7_1.setText(myapp.getLoginItem().getUserNm());
			edit_9_1.setText(exportItem.getdMark());//Distinguish mark
			edit_10_1.setText(exportItem.getRemCd());//부기사항
			edit_10_2.setText(exportItem.getRemNm());//부기사항
			edit_11_1.setText(exportItem.getRemark());//검역관종합의견
			firstLoad=false;
		}
		Log.i("resultFlag", exportItem.getResultFlag());
		if(exportItem.getResultFlag().equals("226001")){
			//합격
			radio_8_1.setChecked(true);
		}else if(exportItem.getResultFlag().equals("226002")){
			//불합격
			radio_8_2.setChecked(true);
		}else{
			//보류
			radio_8_3.setChecked(true);
		}
		
		quncdArrList = exportItem.getQunCdList();
		if(quncdArrList.size() > 0){
			spinQunArrList = new ArrayList<String>();
			for (int i = 0; i < quncdArrList.size(); i++) {
				spinQunArrList.add(quncdArrList.get(i).getCodeNm());
			}
		}
		
		//lmo 데이터 담기
		lmoArrList = exportItem.getLmoList();
		if(lmoArrList.size()>0){
			spinLmoArrList = new ArrayList<String>();
			for(int i=0; i<lmoArrList.size(); i++){
				spinLmoArrList.add(lmoArrList.get(i).getCodeNm());
			}
		}
		
		//사진보기
		if("".equals(exportItem.getImgResult1().trim())){
			url1="";
			castString1="";
		}else{
			url1 = myapp.cameraUtil.photoSetting(exportItem.getImgResult1()).replace("\\", "/");
			new yourTask().execute();
		}
		if("".equals(exportItem.getImgResult2().trim())){
			url2 = "";
			castString2="";
		}else{
			url2 = myapp.cameraUtil.photoSetting(exportItem.getImgResult2()).replace("\\", "/");
			new yourTask().execute();
		}
		button_13_1.setOnClickListener(this);
		button_13_2.setOnClickListener(this);
		
		//검역결과코드리스트
		resultFlagList = exportItem.getResultFlagList();
		//품목정보
		prodArrList = exportItem.getItems();
		for(int i=0; i<prodArrList.size(); i++){
			arrInsQty.add(i, prodArrList.get(i).getInsQty());
			Log.i("position", i+"");
		}
		Log.i("prodArrList.get(position).getInsQty()", arrInsQty.toString());
		Log.i("InsQty().size", arrInsQty.size()+"");
		
		//Log.i("exportItem", exportItem.getItems().get(0).getLmoResult());
		//Log.i("exportItem", exportItem.getItems().get(1).getLmoResult());
		
		//하단 리스트 셋팅
		checkReqIsNull = text_2_1.getText().toString();
		
		headerTotTxt = (TextView)findViewById(R.id.header_tot);
		upBtn = (ImageButton)findViewById(R.id.header_up_btn);
		downBtn = (ImageButton)findViewById(R.id.header_down_btn);
		
		headerTotTxt.setText("총 품목:"+exportItem.getItemsResult()+"건");
		listView.setAdapter(dAdapter);
		
		upBtn.setOnClickListener(this);
		downBtn.setOnClickListener(this);
		downBtn.performClick();
	}
	
	private class yourTask extends AsyncTask<Integer, Void, Integer> {
	    @Override
	    protected void onPreExecute() {
	        super.onPreExecute();
	        //show a progress bar
	    }

	    @Override
	    protected Integer doInBackground(Integer... params) {
	        BitmapDrawable drawable = null;
	        Bitmap bitmap = null;
	        if(!"".equals(url1)){
	        	drawable1  =  myapp.cameraUtil.LoadImageFromWeb(url1);
	        	drawable = (BitmapDrawable)drawable1;
	        	bitmap = drawable.getBitmap();
	        	castString1 = myapp.cameraUtil.castByteArrayToString(myapp.cameraUtil.bitmapToByteArray(bitmap));
	        }
	        if(!"".equals(url2)){
	        	drawable2  =  myapp.cameraUtil.LoadImageFromWeb(url2); 
	        	drawable = (BitmapDrawable)drawable2;
	        	bitmap = drawable.getBitmap();
	        	castString2 = myapp.cameraUtil.castByteArrayToString(myapp.cameraUtil.bitmapToByteArray(bitmap));
	        }
	        return 0; 
	    }      

	    @Override
	    protected void onPostExecute(Integer result) {
	        super.onPostExecute(result);
	        if(!"".equals(castString1.trim())){
	        	detail_layout13_1.setVisibility(View.VISIBLE);
	        	photo_check_mgs.setVisibility(View.GONE);
	        	photo_view.setVisibility(View.VISIBLE);
	        	photo_view.setImageDrawable(drawable1);   
	 	        button_13_1.setVisibility(View.VISIBLE);
	        }
	        if(!"".equals(castString2.trim())){
	        	photo_view2.setVisibility(View.VISIBLE);
	        	photo_view2.setImageDrawable(drawable2);
	 	        button_13_2.setVisibility(View.VISIBLE);
	        }
	    }
	}
	
	// 첨부된 이미지뷰를 체크하여 둘다 없으면 레이아웃을 지운다.
	private void layoutCheck(ImageView v1, ImageView v2) {
		if (v1.getDrawable() == null && v2.getDrawable() == null) {
			detail_layout13_1.setVisibility(View.GONE);
			photo_check_mgs.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	protected void onResume() {
		if(myapp.isFinishState()||myapp.isAbleHome()){
			finish();
		}
		/*if(myapp.isDataLoadState()){
			search_btn.performClick();
			myapp.setDataLoadState(false);
		}*/
		if(myapp.isDataDetailLoadState()){
			myapp.startBroker(context);
			//layoutSetting();
			search_btn.performClick();
			myapp.setDataDetailLoadState(false);
		}
		super.onResume();
	}
	
	//ExportQuarantineResultDetailThreadCallback
	@Override
	public void OnExportQuarantineDetailError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
	}

	//ExportQuarantineResultDetailThreadCallback
	@Override
	public void OnExportQuarantineDetailCompleted(boolean isNetworkConntected,
			ExportQuarantineResultDetailItem exportItem, String message) {
		Log.i("message-->", "message-->"+message);
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(exportItem != null) {
			this.exportItem = exportItem;
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				layoutSetting();
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, "실패", errMsg, 20);
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, "실패", "네트워크에러", 20);
				break;
				
			case MSG_QUARANTINE_UPDATE_COMPLETED:
				new AlertDialog.Builder(ExportQuarantineResultDetail.this)
				.setTitle("저장")
				.setMessage(success)
				.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							searchDetail(prodArrList.get(0).getRecNo());
						} catch (Exception e) {

						}
					}
				})
				.setCancelable(false)
				.show();
				break;
			default:
				break;
			}
		}
	};
	
	//OnClickListener
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHome://홈
			myapp.setAbleHome(true);
			finish();
			break;

		case R.id.search_btn://조회
			String b = edit_request_num.getText().toString();
			Log.i("edit_request_num", "edit_request_num : "+b);
			if(b.length()==8){
				searchDetail(b);
			}else{
				myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, "실패", "검역신청 번호 뒤 8자리를 입력해 주세요.", 20);
			}
			//sliding menu를 테스트하기위한 예제
			//intent = new Intent(ExportQuarantineResultDetail.this, TextDrowMenuActivity.class);
			//startActivity(intent);
			break;
			
		case R.id.text_4_2://연락처
			n = Uri.parse("tel: "+text_4_2.getText());
			startActivity(new Intent(Intent.ACTION_DIAL, n));
			break;
			
		case R.id.edit_7_1://현장검역관에딧1
			edit_7_1.setText("");
			userSn1 = "";
			break;
			
		case R.id.edit_7_2://현장검역관에딧2
			edit_7_2.setText("");
			userSn2 = "";
			break;
			
		case R.id.button_7_1://현장검역관버튼1
			if(edit_7_1.getText().toString().equals(myapp.getLoginItem().getUserNm().toString())){
				edit_7_1.setText("");
			}
			intent = new Intent(ExportQuarantineResultDetail.this, PlaceOfficerActivity.class);
			intent.putExtra("userNm", edit_7_1.getText().toString());
			startActivityForResult(intent, 1);
			break;
			
		case R.id.button_7_2://현장검역관버튼2
			if(edit_7_2.getText().toString().equals(myapp.getLoginItem().getUserNm().toString())){
				edit_7_2.setText("");
			}
			intent = new Intent(ExportQuarantineResultDetail.this, PlaceOfficerActivity.class);
			intent.putExtra("userNm", edit_7_2.getText().toString());
			startActivityForResult(intent, 2);
			break;
			
		case R.id.edit_10_1://부기사항번호
			edit_10_1.setText("");
			break;
			
		case R.id.button_10_1://부기사항버튼
			intent = new Intent(ExportQuarantineResultDetail.this, BuKipActivity.class);
			intent.putExtra("remCd", edit_10_1.getText().toString());
			startActivityForResult(intent, 3);
			break;
			
		case R.id.header_up_btn://리스트 위화살표
			RelativeLayout.LayoutParams listParams = new RelativeLayout.LayoutParams
		    (LayoutParams.WRAP_CONTENT, myapp.utilm.getDpToPixel(context, 400));
			listParams.addRule(RelativeLayout.ABOVE, R.id.bottom_layout);
			listView.setLayoutParams(listParams);
			break;
			
		case R.id.header_down_btn://리스트 아래화살표
			RelativeLayout.LayoutParams listParams1 = new RelativeLayout.LayoutParams
		    (LayoutParams.WRAP_CONTENT, myapp.utilm.getDpToPixel(context, 130));
			listParams1.addRule(RelativeLayout.ABOVE, R.id.bottom_layout);
			listView.setLayoutParams(listParams1);
			break;
			
		case R.id.footer01Btn://목록버튼
			onBackPressed();
			break;
			
		case R.id.footer02Btn://저장버튼
			//저장버튼 누르면 현장검역관 EditText에 아무것도 
			//안썻을경우 userSn1, userSn2 에 아무것도 넣지 않는다.
			if(edit_7_1.getText().toString().equals("")){
				userSn1="";
				myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, "실패", "현장검역관을 입력하세요.", 20);
				return;
			}
			/*if(prodArrList.get(position).getCountryYn().toString().equals("Y")){
				myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, "실패", "선과장을 등록 해주세요.", 20);
				return;
			}*/
			if(edit_7_2.getText().toString().equals("")){
				userSn2="";
			}
			
			if(text_2_2.getText().toString().trim().equals("결재완료")){
				myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, "실패", "이미 저장 하였습니다.", 20);
				return;
			}
			
			resultSave();
			break;
			
		case R.id.footer03Btn://결재
			//저장을 안하면....
			if(exportItem.getResultProgrsSt().equals("377002")){
				for (int i = 0; i < prodArrList.size(); i++) {
					if(!arrInsQty.get(i).replace(",", "").equals(prodArrList.get(i).getInsQty().replace(",", ""))){
						myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, "실패", "저장을 먼저 해주세요.",20);
						return;
					}
					if (Float.parseFloat(prodArrList.get(i).getInsQty().replace(",", "")) != Float.parseFloat(prodArrList.get(i).getItmQty().replace(",", ""))) {
						myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, "실패", "합격수량이 검역수량과 같아야 결재 가능 합니다.",20);
						return;
					}
				}
				myapp.setDataLoadState(true);
				intent = new Intent(ExportQuarantineResultDetail.this, ApproveDetail.class);
				intent.putExtra("resNo", exportItem.getResNo());
				intent.putExtra("resOffCd", exportItem.getResOffCd());
				intent.putExtra("value", "0");
				startActivity(intent);
			}else if(countryYnCheck()){
				//countryYn 널이면 안보이게 N이면 등록안한거 빨강, 등록한거 Y 파랑 ,파랑이면 결재안되게
				myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, "실패", "선과장 등록을 해주세요.", 20);
				return;
			}else{
				myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, "실패", "저장을 먼저 해주세요.", 20);
				return;
			}
			break;
			
		case R.id.footer04Btn: //사진
			if(!castString1.trim().equals("") && !castString2.trim().equals("")){
				myapp.utilm.ShowDialog(context, "실패", "사진은 2장 까지 가능 합니다.", 20);
			}else{
				intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("/sdcard/image.jpg")));
				startActivityForResult(intent, 5);
			}
			break;
			
		case R.id.button_13_1:
			photo_view.setImageDrawable(null);
			photo_view.setVisibility(View.GONE);
			button_13_1.setVisibility(View.GONE);
			castString1="";
			url1="";
			layoutCheck(photo_view, photo_view2);
			break;
			
		case R.id.button_13_2:
			photo_view2.setImageDrawable(null);
			photo_view2.setVisibility(View.GONE);
			button_13_2.setVisibility(View.GONE);
			castString2="";
			url2="";
			layoutCheck(photo_view, photo_view2);
			break;
		}
	}
	
	public boolean countryYnCheck(){
		boolean value=false;
		for(int i=0; i<prodArrList.size(); i++){
			if(prodArrList.get(i).getCountryYn().toString().equals("N")){
				value=true;
			}
		}
		return value;
	}
	
	//저장버튼
	private void resultSave(){
		resultDetail = new JSONObject();
		resultData = new JSONObject();
		JSONObject resultMaster = new JSONObject();
		JSONArray requestArray = new JSONArray();
		JSONArray lmoResult = new JSONArray();
		JSONObject obj;
		String SitmQty ="";
		String SinsQty ="";
		String resultCode = "";
		
		if(radio_8_1.isChecked()){
			resultCode = exportItem.getResultFlagList().get(0).getCode();
		}else if(radio_8_2.isChecked()){
			resultCode = exportItem.getResultFlagList().get(1).getCode();
		}else if(radio_8_3.isChecked()){
			resultCode = exportItem.getResultFlagList().get(2).getCode();
		}else{
			myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, "실패", "검역결과를 선택해 주세요.", 20);
			return;
		}
		Log.i("resultCode", "resultCode : "+resultCode);
		
		for (int i = 0; i < prodArrList.size(); i++) {
			View v = dAdapter.getView(i, null, listView);
			EditText editText=(EditText) v.findViewById(R.id.detail_list_ins_qty);
			
			Log.i("getItmQty", "getItmQty :: "+prodArrList.get(i).getItmQty());
			
			SitmQty = prodArrList.get(i).getItmQty()==null? "":prodArrList.get(i).getItmQty();
			SinsQty = prodArrList.get(i).getInsQty()==null? "":prodArrList.get(i).getInsQty();
			
			float itmQty = 0f;
			float insQty = 0f;
			
			if(!"".equals(SitmQty)){
				itmQty = Float.parseFloat(prodArrList.get(i).getItmQty().replace(",", ""));
			}
			if(!"".equals(SinsQty)){
				insQty = Float.parseFloat(prodArrList.get(i).getInsQty().replace(",", ""));
			}
			
			if(insQty > itmQty){
				myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, 
						"실패", "합격수량이 검역수량을 초과할 수 없습니다", 20);
				return;
			}
			
			try {
				obj = new JSONObject();
				obj.put("offCd", prodArrList.get(i).getOffCd());
				obj.put("recNo", prodArrList.get(i).getRecNo());
				obj.put("recSeq", prodArrList.get(i).getRecSeq());
				obj.put("insQty", String.valueOf(insQty));
				obj.put("itmQty", String.valueOf(itmQty));
				obj.put("qunCd", prodArrList.get(i).getQunCd());
				obj.put("itemType", prodArrList.get(i).getItemType());
				obj.put("updNamCd", myapp.getLoginItem().getUserSn());
				//lmoResult 저장시 보내기
				obj.put("lmoResult", prodArrList.get(i).getLmoResult());
				Log.i("obj", obj.toString());
				
				//선과장 버튼클릭시 검역결과순번을 넣어서 인텐트로 전달
				resSeq = prodArrList.get(i).getRecSeq();
				
				requestArray.put(obj);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		try {
			resultMaster.put("resOffCd", exportItem.getResOffCd());
			resultMaster.put("resNo", exportItem.getResNo());
			resultMaster.put("regType", exportItem.getRegType());
			resultMaster.put("offCd", exportItem.getOffCd());
			resultMaster.put("recNo", recNo);
			Log.i("new RecNo","->"+recNo);
			//resultMaster.put("validflag", exportItem.getValidflag());
	        //resultMaster.put("passResrveReasonCd", exportItem.getDelaysayu()); /*합격보류사유*/
	        resultMaster.put("fieArea", edit_6_1.getText().toString()); 
	        resultMaster.put("quranCd1", userSn1);
	        resultMaster.put("quranCd2", userSn2);
	        resultMaster.put("remark", edit_11_1.getText().toString());
	        resultMaster.put("updNamCd", myapp.getLoginItem().getUserSn());
	        resultMaster.put("remCd",edit_10_1.getText().toString());//부기사항코드
	        resultMaster.put("resultFlag", resultCode );//검역결과값
	        resultMaster.put("dMark",edit_9_1.getText().toString());//마크값
	        //사진
			if(castString1.equals("")&&!castString2.equals("")){
				castString1=castString2;
				castString2="";
				button_13_2.performClick();
			}
	        resultMaster.put("imgResult1", castString1);
			resultMaster.put("imgResult2", castString2);
			resultMaster.put("fileId", exportItem.getFileId());

	        resultData.put("resultMaster", resultMaster);
	        resultDetail.put("resultDetail", requestArray);
	        
	        Log.i("resultMaster",resultMaster.toString());
	        Log.i("resultDetail",requestArray.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		myapp.showDialogNo(context);
		temp = "저장";
		//asyncTaskIsConnectedVPN();
		threadStart();
		
	}
	
	//요청1 : 현장검역관1 요청2 : 현장검역관2 요청3 : 부기사항
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1:
			if(resultCode == 1){
				edit_7_1.setText(data.getStringExtra("userNm"));
				userSn1 = data.getStringExtra("userSn");
			}else{
				Log.i("resultCode","resultCode  0 아님");
			}
			break;
			
		case 2:
			if(resultCode == 1){
				edit_7_2.setText(data.getStringExtra("userNm"));
				userSn2 = data.getStringExtra("userSn");
			}else{
				Log.i("resultCode","resultCode  0 아님");
			}
			break;

		case 3: //부기사항버튼
			if(resultCode == 1){
				edit_10_1.setText(data.getStringExtra("bukipCd"));
				edit_10_2.setText(data.getStringExtra("bukipNm"));
			}else{
				Log.i("resultCode","resultCode  0 아님");
			}
			break;
	
		case 4://선과장
			search_btn.performClick();
			break;
			
		//사진
		case 5:
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 4;
			Bitmap captureBmp = BitmapFactory.decodeFile("/sdcard/image.jpg", options);
			if(captureBmp != null){
				Bitmap resized = Bitmap.createScaledBitmap(captureBmp, 740, 420, true);
				
				Matrix m = new Matrix();
				m.setRotate(90, (float) resized.getWidth() / 2, (float) resized.getHeight() / 2 );
				try{
					Bitmap b2 = Bitmap.createBitmap(resized, 0, 0, resized.getWidth(), resized.getHeight(), m, true);
					if(resized != b2){
						resized.recycle();
					}
					resized = b2;
				}catch (OutOfMemoryError ex){
				
				}
				
				detail_layout13_1.setVisibility(View.VISIBLE);
				photo_check_mgs.setVisibility(View.GONE);
				if(photo_view.getDrawable() == null){
					photo_view.setVisibility(View.VISIBLE);
					button_13_1.setVisibility(View.VISIBLE);
					System.out.println("비트맵 싸이즈->"+resized.getWidth());
					System.out.println("비트맵 싸이즈->"+resized.getHeight());
					photo_view.setImageBitmap(resized);
					castString1=(myapp.cameraUtil.castByteArrayToString(myapp.cameraUtil.bitmapToByteArray(resized)));
				}else if(photo_view2.getDrawable() == null){
					photo_view2.setVisibility(View.VISIBLE);
					button_13_2.setVisibility(View.VISIBLE);
					System.out.println("비트맵 싸이즈->"+resized.getWidth());
					System.out.println("비트맵 싸이즈->"+resized.getHeight());
					photo_view2.setImageBitmap(resized);
					castString2=(myapp.cameraUtil.castByteArrayToString(myapp.cameraUtil.bitmapToByteArray(resized)));
				}
				
				File f = new File("/sdcard/image.jpg");
				if(f.exists())
				{
					f.delete();
				}
			}
			break;
			
		default:
			break;
		}
	}
	
	class ExportQuarantineResultDetailAdapter extends BaseAdapter {
		TextView detail_list_seq, detail_list_trfclsf_cd;
		TextView detail_list_itm_qty, detail_list_prod_name, quran_result;
		EditText detail_list_ins_qty;
		Spinner list_detail_spin, spinner;
		ImageButton button01;
		RelativeLayout layout_quran_result;
		
		@Override
		public int getCount() {
			return prodArrList.size();
		}

		@Override
		public Object getItem(int position) {
			return prodArrList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_export_result_item, parent, false);
    		}
			detail_list_seq = (TextView)convertView.findViewById(R.id.detail_list_seq);
			detail_list_trfclsf_cd = (TextView)convertView.findViewById(R.id.detail_list_trfclsf_cd);
			detail_list_itm_qty = (TextView)convertView.findViewById(R.id.detail_list_itm_qty);
			list_detail_spin = (Spinner)convertView.findViewById(R.id.list_detail_spin);
			detail_list_prod_name = (TextView)convertView.findViewById(R.id.detail_list_prod_name);
			detail_list_ins_qty = (EditText)convertView.findViewById(R.id.detail_list_ins_qty);
			button01 = (ImageButton)convertView.findViewById(R.id.button01);
			spinner = (Spinner)convertView.findViewById(R.id.spinner);
			layout_quran_result = (RelativeLayout)convertView.findViewById(R.id.layout_quran_result);
			
			quran_result= (TextView)convertView.findViewById(R.id.quran_result);
			quran_result.setText("검역결과");
			
			//버튼 셋팅 : checkReqIsNull(검역결과번호) 가 널이면 안보이게 아니면 보이게
			//test
			//button01.setVisibility(View.VISIBLE);
			//button01.setBackgroundResource(R.drawable.btn_sunred);
			//noTest
			button01.setVisibility(View.GONE);
			if(!"".equals(checkReqIsNull.toString())){
				Log.i("getCountryYn", "getCountryYn : " + prodArrList.get(position).getCountryYn());
				if(prodArrList.get(position).getCountryYn().toString().equals("Y")){
					button01.setVisibility(View.VISIBLE);
					button01.setBackgroundResource(R.drawable.btn_sunblue);
					
				}
				if(prodArrList.get(position).getCountryYn().toString().equals("N")){//N일때
					button01.setVisibility(View.VISIBLE);
					button01.setBackgroundResource(R.drawable.btn_sunred);
				}
			}
			button01.setOnClickListener(new OnClickListener() {
				//선과장을 눌렀을때
				@Override
				public void onClick(View v) {
					intent = new Intent(ExportQuarantineResultDetail.this, FruitPackingActivity.class);
					intent.putExtra("resOffCd", exportItem.getOffCd());
					intent.putExtra("resNo", exportItem.getResNo());
					intent.putExtra("recSeq", exportItem.getItems().get(position).getRecSeq());
					startActivityForResult(intent, 4);
					/*if(prodArrList.get(position).getCountryYn().toString().equals("Y")){
						myapp.utilm.ShowDialog(ExportQuarantineResultDetail.this, "실패", "이미 선과장 등록을 하였습니다.", 20);
						return;
					}else{
						intent = new Intent(ExportQuarantineResultDetail.this, FruitPackingActivity.class);
						intent.putExtra("resOffCd", exportItem.getOffCd());
						Log.i("resOffCd", exportItem.getOffCd());
						intent.putExtra("resNo", exportItem.getResNo());
						Log.i("recNo", exportItem.getRecNo());
						intent.putExtra("recSeq", exportItem.getItems().get(position).getRecSeq());
						Log.i("recSeq", exportItem.getItems().get(position).getRecSeq().toString());
						startActivityForResult(intent, 4);
					}*/
				}
			});
			if(prodArrList.get(position).getLmoResultYn().equals("Y")){
				layout_quran_result.setVisibility(View.VISIBLE);
			}
			lmoAdapter = new ArrayAdapter<String>(context, R.layout.spinner_item, spinLmoArrList);
			spinner.setAdapter(lmoAdapter);
			spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
				@Override
				public void onItemSelected(AdapterView<?> parent, View view, int count, long id) {
					//code.add(exportItem.getLmoList().get(position).getCode());
					//prodArrList.get(position).
					prodArrList.get(position).setLmoResult(lmoArrList.get(count).getCode());
				}
				@Override
				public void onNothingSelected(AdapterView<?> parent) {}
			});
			for(int i=0; i<lmoArrList.size(); i++){
				if(lmoArrList.get(i).getCode().equals(prodArrList.get(position).getLmoResult())){
					spinner.setSelection(i);
				}
			}
			/*button02.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Toast.makeText(context, "구현중", Toast.LENGTH_SHORT).show();
				}
			});*/
			detail_list_seq.setText(prodArrList.get(position).getRecSeq());
			detail_list_trfclsf_cd.setText(prodArrList.get(position).getPrdlstCode());
			detail_list_itm_qty.setText(prodArrList.get(position).getItmQty());
			detail_list_prod_name.setText(prodArrList.get(position).getPrdlstNm());
			detail_list_ins_qty.setText(prodArrList.get(position).getInsQty());
			detail_list_ins_qty.addTextChangedListener(new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
				}
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
				}
				@Override
				public void afterTextChanged(Editable s) {
					prodArrList.get(position).setInsQty(s.toString());
				}
			});
			
			qunAdapter = new ArrayAdapter<String>(context,  R.layout.spinner_item, spinQunArrList);
			list_detail_spin.setAdapter(qunAdapter);
			list_detail_spin.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int count, long id) {
					prodArrList.get(position).setQunCd(quncdArrList.get(count).getCode());
				}
				@Override
				public void onNothingSelected(AdapterView<?> parent) {}
			});
			for (int i = 0; i < quncdArrList.size(); i++) {
				if(quncdArrList.get(i).getCode().equals(prodArrList.get(position).getQunCd())){
					list_detail_spin.setSelection(i);
				}
			}
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			return convertView;
		}
		private void listItemClickEvent(final int position) {
		}
	}
	
	//ExportQuarantineUpdateThreadCallBack
	@Override
	public void OnExportQuarantineCompleted(boolean isNetworkConntected,
			String result, String message) {
		Log.i("message-->", "message-->"+message);
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		if(!result.equals("")) {
			this.success = result;
			//저장이완료되면 리로딩이 되어야 한다.
			myapp.setDataLoadState(true);
			
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_UPDATE_COMPLETED;
			handler.sendMessage(msg);
		}
	}

	//ExportQuarantineUpdateThreadCallBack
	@Override
	public void OnExportQuarantineError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
		
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppStatus.navigation.delPathLocation();
	}

	private void reesultToast() {
		runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }	
	
}
